<template>
  <div class="app-container">
    <div class="head-container">
      <label class="el-form-item-label">{{ $t('dismantling.username') + ':' }}</label>
      <label class="el-form-item-label" style="margin-right: 40px;">{{ user.username }}</label>
      <label class="el-form-item-label">{{ $t('dismantling.stationId') + ':' }}</label>
      <label class="el-form-item-label" style="margin-right: 40px;">{{ scanForm.stationId }}</label>
      <label class="el-form-item-label">{{ $t('dismantling.palletCode') + ':' }}</label>
      <label class="el-form-item-label">{{ addForm.palletCode }}</label>
      <el-card style="margin-top: 30px;">
        <el-descriptions
          :title="$t('dismantling.processcardInfo')"
          size="medium"
          :content-style="{ 'font-size': '32px' }"
          :label-style="{ 'font-size': '32px' }"
        >
          <el-descriptions-item :label="$t('dismantling.id')">{{ addForm.id }}</el-descriptions-item>
          <el-descriptions-item :label="$t('dismantling.processcardCode')">{{ addForm.processcardCode }}</el-descriptions-item>
          <el-descriptions-item :label="$t('laminationCraft.workNum')">{{ addForm.workNum }}</el-descriptions-item>
          <el-descriptions-item :label="$t('dismantling.productType')">{{ addForm.productType }}</el-descriptions-item>
          <el-descriptions-item :label="$t('dismantling.size1')">{{ addForm.size1 }}</el-descriptions-item>
          <el-descriptions-item :label="$t('dismantling.size2')">{{ addForm.size2 }}</el-descriptions-item>
          <el-descriptions-item :label="$t('dismantling.material')">{{ addForm.material }}</el-descriptions-item>
          <el-descriptions-item :label="$t('dismantling.thick')">{{ addForm.thick }}</el-descriptions-item>
          <el-descriptions-item :label="$t('dismantling.layerName')">{{ addForm.layerName }}</el-descriptions-item>
          <el-descriptions-item :label="$t('dismantling.qty')">{{ addForm.qty }}</el-descriptions-item>
          <el-descriptions-item v-if="palletList.length > 0 && count" :label-style="{ display: 'none' }">
            <div style="display: flex;flex-direction: column;gap: 5px;font-size: x-large;font-weight: 700;">
              <div>拆解单未拆解载盘列表（载盘总数为[{{ count }}]）</div>
              <div style="color: #F56C6C;">{{ palletList.join('、') }}</div>
            </div>
          </el-descriptions-item>
        </el-descriptions>
        <div class="rightbutton">
          <el-button type="primary" size="medium" @click="getMsg">{{ $t('dismantling.getMsg') }}</el-button>
          <el-button v-permission="['admin','forceOrder:clear']" type="danger" size="medium" @click="dialogVisible = true">{{ $t('dismantling.force') }}</el-button>
        </div>
      </el-card>
      <!-- 表单渲染 -->
      <el-dialog
        title="提示"
        :visible.sync="dialogVisible"
        width="30%"
      >
        <span>{{ $t('dismantling.tipText') }}</span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">{{ $t('crud.cancel') }}</el-button>
          <el-button type="primary" @click="forceOrder">{{ $t('crud.confirm') }}</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { getMsg, forceOrderAPI, getStationDetailAPI } from '@/api/workStation'
import { mapGetters } from 'vuex'
import { EventSourcePolyfill } from 'event-source-polyfill'
import { getToken } from '@/utils/auth'
export default {
  data() {
    return {
      dialogVisible: false,
      items: [
        { type: 'danger', label: 'OFF' },
        { type: 'success', label: 'ON' },
        { type: 'success', label: 'ON' },
        { type: 'danger', label: 'OFF' }
      ],
      leftformLabelWidth: '100px',
      rightformLabelWidth: '80px',
      addForm: {},
      scanForm: {
        processcardCode: '',
        stationId: '',
        palletCode: ''
      },
      formRules: {},
      timer: null,
      es: null,
      lastTime: '',
      nextTime: '',
      lastCode: '',
      nextCode: '',
      count: 0,
      palletList: []
    }
  },
  computed: {
    ...mapGetters([
      'user'
    ])
  },
  mounted() {
    this.getSSE()
    this.scanForm.stationId = this.$route.query.stationCode
  },
  beforeDestroy() {
    clearInterval(this.timer)
  },
  methods: {
    async getStationDetail(val) {
      const res = await getStationDetailAPI(val)
      if (res.meta.code === 200) {
        const entries = Object.entries(res.data.UnbindingStationsDetail.palletStatus)
        this.palletList = entries.filter(([code, status]) => status === 1).map(([code]) => Number(code))
        this.count = res.data.UnbindingStationsDetail.count
      }
    },
    forceOrder() {
      forceOrderAPI(this.scanForm.stationId).then(res => {
        if (res.meta.code === 200) {
          this.$message.success(res.meta.msg)
          this.dialogVisible = false
        } else {
          this.$message.error(res.meta.msg)
        }
      })
    },
    getMsg() {
      getMsg(this.addForm.palletCode).then(data => {
        if (data.meta.code === 200) {
          this.addForm = data.data.inventory
          this.$message.success(data.meta.msg)
          // this.getStationDetail(this.addForm.palletCode)
        } else {
          this.$message.error(data.meta.msg)
          this.scanForm.palletCode = ''
        }
      }).catch((err) => {
        this.$message.error(err)
      })
    },
    getSSE() {
      const base = process.env.VUE_APP_BASE_API
      const url = `${base}/unbinding`
      const that = this
      this.es = new EventSourcePolyfill(url, {
        headers: { 'Authorization': getToken() }
      })

      this.es.onopen = function(event) {
        console.log('连接成功', event)
      }

      this.es.onmessage = function(event) {
        // to to something…
        const data = JSON.parse(event.data).data.inventory
        that.addForm = data[`${that.scanForm.stationId}`]
        that.getStationDetail(that.addForm.palletCode)
      }

      this.es.onerror = function(error) {
        // 监听错误
        console.log('错误', error)
        // that.handleError()
      }
    },
    // 错误重连事件
    handleError() {
      if (this.es.readyState === EventSourcePolyfill.CLOSED) {
        this.es.close()
        this.getSSE()
      } else if (this.es.readyState === EventSourcePolyfill.CONNECTING) {
        console.log('正在重连中')
      }
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
::v-deep .el-descriptions--medium:not(.is-bordered) .el-descriptions-item__cell {
  padding-bottom: 36px;
}

::v-deep .el-descriptions__title {
  font-size: 36px;
}

label {
  font-size: 36px !important;
}
</style>
